package com.htudata.hieyes.alarm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import com.htudata.common.enums.RequestSeqEnum;
import com.htudata.common.service.DataEhcacheService;
import com.htudata.convention.domain.ResponseResult;
import com.htudata.core.util.ResultGenerator;
import com.htudata.hieyes.alarm.dao.AlarmStatisDao;
import com.htudata.hieyes.alarm.pojo.po.AlarmLevelPO;
import com.htudata.hieyes.alarm.service.AlarmLevelService;
import com.htudata.hieyes.alarm.service.AlarmStatisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AlarmStatisServiceImpl implements AlarmStatisService {

  @Autowired
  private DataEhcacheService dataEhcacheService;
  
  @Autowired
  private AlarmLevelService alarmLevelService;
  
  @Autowired
  private AlarmStatisDao alarmStatisDao;
  
  private final String ALARMDISTRIBUTION = "1";
  
  private final String CLASSIFICATIONALARM = "2";
  
  private final String HISTORYALARMLEVEL = "3";
  
  @Value("${normal_level}")
  private int normalLevel;

  @Override
  public String getAlarmStatisDataJson(boolean needJudgeChange, String alarmType)  throws Exception{
    ResponseResult responseResult = null;
    try {
      responseResult = ResultGenerator.genResult(RequestSeqEnum.SEQ_001.getCode(), getAlarmStatisData(alarmType));
    } catch (Exception e) {
      throw e;
    } 
    String result = JSON.toJSONString(responseResult);
    if (!needJudgeChange)
      return result; 
    Object temp = this.dataEhcacheService.getValueFromCache(RequestSeqEnum.SEQ_001.getCode());
    if (temp != null) {
      String oldJson = (String)temp;
      if (oldJson.equals(result))
        return null; 
    } 
    this.dataEhcacheService.putValueToCache(RequestSeqEnum.SEQ_001.getCode(), result);
    return result;
  }

  @Override
  public JSONArray getAlarmStatisData(String alarmType)  throws Exception{
    String[] types = alarmType.split(",");
    JSONArray data = new JSONArray();
    for(String type : types){
      if ("1".equals(type)) {
        data.add(getAlarmDistributionData());
      } else if ("2".equals(type)) {
        data.add(getClassificationAlarmData());
      } else if ("3".equals(type)) {
        data.add(getHistoryAlarmLevelData());
      }
    }
    return data;
  }


  @Override
  public JSONObject getAlarmDistributionData()  throws Exception{
    JSONArray alarmDistributionData = new JSONArray();
    JSONArray localProblems = this.alarmStatisDao.selectNodeProblems(0L, 0L);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList();
    alarmLevelList.forEach(alarmLevel -> {
          JSONObject alarmLevelObject = new JSONObject(true);
          alarmLevelObject.put("name", alarmLevel.getName());
          alarmLevelObject.put("value", Integer.valueOf(0));
          alarmLevelObject.put("color", alarmLevel.getColor());
          alarmLevelObject.put("level", Integer.valueOf(alarmLevel.getLevel()));
          alarmDistributionData.add(alarmLevelObject);
        });
    localProblems.forEach(object -> {
          JSONObject localProblem = (JSONObject)object;
          AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, localProblem.getIntValue("level"));
          alarmDistributionData.forEach((m)->{


          });
        });
    JSONObject itemCount = this.alarmStatisDao.countItems();
    long perfectlyNormalValue = itemCount.getLongValue("item_count") - localProblems.size();
    alarmDistributionData.forEach(alarmLevelObject -> {
          JSONObject alarmLevel = (JSONObject)alarmLevelObject;
          if (alarmLevel.getIntValue("level") == this.normalLevel)
            alarmLevel.put("value", Long.valueOf(perfectlyNormalValue)); 
        });
    JSONObject result = handleResult(alarmDistributionData, "告警分布");
    return result;
  }

  @Override
  public JSONObject getClassificationAlarmData()  throws Exception{
    JSONArray classificationAlarmData = new JSONArray();
    JSONObject jsonObject1 = new JSONObject();
    jsonObject1.put("name", "业务指标");
    jsonObject1.put("value", Integer.valueOf(0));
    jsonObject1.put("color", "#6bf2ff");
    jsonObject1.put("type", Integer.valueOf(4));
    classificationAlarmData.add(jsonObject1);
    JSONObject jsonObject2 = new JSONObject();
    jsonObject2.put("name", "软件服务");
    jsonObject2.put("value", Integer.valueOf(0));
    jsonObject2.put("color", "#30c2ff");
    jsonObject2.put("type", Integer.valueOf(3));
    classificationAlarmData.add(jsonObject2);
    JSONObject jsonObject3 = new JSONObject();
    jsonObject3.put("name", "系统服务");
    jsonObject3.put("value", Integer.valueOf(0));
    jsonObject3.put("color", "#034cf8");
    jsonObject3.put("type", Integer.valueOf(2));
    classificationAlarmData.add(jsonObject3);
    JSONObject jsonObject4 = new JSONObject();
    jsonObject4.put("name", "基础资源");
    jsonObject4.put("value", Integer.valueOf(0));
    jsonObject4.put("color", "#5c25e9");
    jsonObject4.put("type", Integer.valueOf(1));
    classificationAlarmData.add(jsonObject4);
    JSONArray localProblems = this.alarmStatisDao.selectNodeProblems(0L, 0L);
    localProblems.forEach(object -> {
          JSONObject localProblem = (JSONObject)object;
          classificationAlarmData.forEach((m)->{



          });
        });
    JSONObject result = handleResult(classificationAlarmData, "分类告警");
    return result;
  }

  @Override
  public JSONObject getHistoryAlarmLevelData()  throws Exception{
    JSONObject historyAlarmLevelData = new JSONObject(true);
    LocalDateTime endTime = LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai")));
    LocalDateTime startTime = endTime.minusMonths(12L);
    historyAlarmLevelData.put("dateTime", new String[12]);
    historyAlarmLevelData.put("xdata", new String[12]);
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM");
    for (int i = 0; i < 12; i++) {
      int month = i + 1;
      LocalDateTime dateTime = startTime.plusMonths(month);
      ((String[])historyAlarmLevelData.getObject("xdata", String[].class))[i] = dateTime.getMonthValue() + "月";
      ((String[])historyAlarmLevelData.getObject("dateTime", String[].class))[i] = format.format(dateTime);
    } 
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    long endTimeInt = Long.parseLong(df.format(endTime));
    long startTimeInt = Long.parseLong(df.format(startTime));
    JSONArray localProblems = this.alarmStatisDao.selectNodeProblems(startTimeInt, endTimeInt);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList();
    JSONArray ydata = new JSONArray();
    alarmLevelList.forEach(alarmLevel -> {
          JSONObject alarmLevelObject = new JSONObject();
          alarmLevelObject.put("name", alarmLevel.getName());
          alarmLevelObject.put("data", new int[12]);
          alarmLevelObject.put("color", alarmLevel.getColor());
          alarmLevelObject.put("level", Integer.valueOf(alarmLevel.getLevel()));
          ydata.add(alarmLevelObject);
        });
    historyAlarmLevelData.put("ydata", ydata);
    localProblems.forEach(object -> {
          JSONObject localProblem = (JSONObject)object;
          AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, localProblem.getIntValue("level"));
          historyAlarmLevelData.getJSONArray("ydata").forEach((m)->{



          });
        });
    JSONObject result = handleResult(historyAlarmLevelData, "历史告警分级统计");
    return result;
  }
  
  public JSONObject handleResult(Object data, String desc) {
    JSONObject result = new JSONObject(true);
    result.put("desc", desc);
    result.put("data", data);
    return result;
  }

  @Override
  public JSONObject getDataCollectAlarm()  throws Exception{
    JSONObject result = new JSONObject();
    result.put("statis", this.alarmStatisDao.getDataCollectStatis());
    JSONArray arr = new JSONArray();
    JSONArray a1 = this.alarmStatisDao.getDataCollectAlarm("his_str");
    JSONArray a2 = this.alarmStatisDao.getDataCollectAlarm("his");
    arr.addAll((Collection)a1);
    arr.addAll((Collection)a2);
    result.put("table", arr);
    return result;
  }

  @Override
  public JSONObject getDataCollectAlarm2()  throws Exception{
    JSONObject result = new JSONObject();
    result.put("statis", this.alarmStatisDao.getDataCollectStatis());
    JSONArray arr = new JSONArray();
    JSONArray a1 = this.alarmStatisDao.getDataCollectAlarm("his_str");
    JSONArray a2 = this.alarmStatisDao.getDataCollectAlarm("his");
    arr.addAll((Collection)a1);
    arr.addAll((Collection)a2);
    result.put("table", arr);
    return result;
  }

  @Override
  public JSONObject getDataCollectAlarm3()  throws Exception{
    JSONArray allItem = this.alarmStatisDao.getAllCollectItems();
    int failCount = 0;
    for (int i = 0; i < allItem.size(); i++) {
      JSONObject temp = allItem.getJSONObject(i);
      if (temp.getInteger("alarmLevel").intValue() != -1) {
        temp.put("value", "异常");
        failCount++;
      } else {
        temp.put("value", "正常");
      } 
    } 
    JSONObject statis = new JSONObject();
    statis.put("failCount", Integer.valueOf(failCount));
    statis.put("successCount", Integer.valueOf(allItem.size() - failCount));
    JSONObject result = new JSONObject();
    result.put("statis", statis);
    result.put("table", allItem);
    return result;
  }

  @Override
  public String getDataCollectAlarmJSON()  throws Exception{
    ResponseResult responseResult = null;
    try {
      responseResult = ResultGenerator.genResult(RequestSeqEnum.SEQ_010.getCode(), getDataCollectAlarm());
    } catch (Exception e) {
      throw e;
    } 
    String result = JSON.toJSONString(responseResult);
    return result;
  }

  @Override
  public String getDataCollectAlarm2JSON()  throws Exception{
    ResponseResult responseResult = null;
    try {
      responseResult = ResultGenerator.genResult(RequestSeqEnum.SEQ_010.getCode(), getDataCollectAlarm2());
    } catch (Exception e) {
      throw e;
    } 
    String result = JSON.toJSONString(responseResult);
    return result;
  }
}
